package win.devhu.testing.simple.jsoupdemo

import com.github.kittinunf.fuel.Fuel
import org.jsoup.HttpStatusException
import org.jsoup.Jsoup
import org.slf4j.LoggerFactory
import java.io.File

/**
 * jenkins 插件下载
 */
class JenkinsPlugins
private  var logger = LoggerFactory.getLogger(JenkinsPlugins::class.java)

fun main(args: Array<String>){
    print("插件名称: ")
    val pluginsInput = readLine()!!

    var pluginName = "/${pluginsInput.trim()}"
    val depSet = mutableSetOf<String>()
    logger.info("获取相关依赖")
    getDependencies(pluginName,depSet)
    val pluginDirectory = "plugins"
    for(dep in depSet){
        val saveName = "$pluginDirectory$dep.hpi"
        val downloadUrl = "https://mirrors.tuna.tsinghua.edu.cn/jenkins/plugins$dep/latest$dep.hpi"
        logger.info("正在下载：$saveName  下载地址：$downloadUrl")
        download(saveName,downloadUrl)
    }
}
//通过官方插件页面爬取插件依赖，容易超时。
fun getDependencies(pluginName: String,depSet:MutableSet<String>){
    val baseURL = "http://plugins.jenkins.io$pluginName"
//    println("当前URL$baseURL")
    try {
        val doc = Jsoup.connect(baseURL).timeout(10000).ignoreContentType(true).get()
        val links = doc.select(".required").select("a[href]")   //获取required级别的必须依赖
        if(!links.isEmpty()){
            for (link in links){
                val href = link.attr("href")    //依赖组件的地址
                if(!depSet.contains(href)){     //不存在则添加
                    depSet.add(href)
                    getDependencies(href,depSet)    //递归爬取依赖插件的依赖
                }
            }
        }
        depSet.add(pluginName)  //添加自身

    }catch (e:NullPointerException){
        e.printStackTrace()
    }catch (e:HttpStatusException){
        e.printStackTrace()
    }
}

/**
 * 根据下载地址和保存名称下载
 */
fun download(saveName:String,downloadUrl:String){
    var file = File(saveName)
    if(file.exists()){
        logger.info("$saveName 已存在跳过")
    } else {
        Fuel.download(downloadUrl)
                .destination { response, url -> File(saveName).apply { logger.info("保存路径：$absolutePath") } }
                .responseString()
    }
}
